package com.zh.business.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.zh.business.vo.web.PermissionVo;
import com.zh.zhbootcommon.entity.user.Permission;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 工具类
 *
 * @author: yanglin
 * @Date: 2021-07-29-9:06
 * @Version: 1.0
 */
public class CommonUtils {

    /**
     * 用户登录有效时间
     */
    public final static long USER_LOGIN_EXPIRE = 12 * 60 * 60;

    /**
     * TOKEN 幂等性 有效时间
     */
    public final static long MP_TOKEN_EXPIRE = 10;

    /**
     * 当前时间的前1分钟的时间
     * 结果：newDate = 2020-12-24 13:45:40 Before=2020-12-24 13:44:40
     *
     * @return
     */
    public static String getOneMinuteBeforeTime() {
        Date newDate = DateUtil.offset(DateUtil.date(), DateField.MINUTE, -1);
        String startTime = DateUtil.format(newDate, "yyyy-MM-dd HH:mm:ss");
        return startTime;
    }

    /**
     * 当前时间的前1分钟的时间
     *
     * @param now
     * @return
     */
    public static String getOneMinuteBeforeTime(String now) {
        Date date = DateUtil.parse(now);
        Date newDate = DateUtil.offset(date, DateField.MINUTE, -1);
        String startTime = DateUtil.format(newDate, "yyyy-MM-dd HH:mm:ss");
        return startTime;
    }

    /**
     * 当前时间的后1个分钟的时间
     * 结果：newDate = 2020-12-24 13:45:40 Before=2020-12-24 13:46:40
     *
     * @return
     */
    public static String getOneMinuteAfterTime() {
        Date newDate = DateUtil.offset(DateUtil.date(), DateField.MINUTE, 1);
        String startTime = DateUtil.format(newDate, "yyyy-MM-dd HH:mm:ss");
        return startTime;
    }

    /**
     * 当前时间的后1个分钟的时间
     * 结果：newDate = 2020-12-24 13:45:40 Before=2020-12-24 13:46:40
     *
     * @param now
     * @return
     */
    public static String getOneMinuteAfterTime(String now) {
        Date date = DateUtil.parse(now);
        Date newDate = DateUtil.offset(date, DateField.MINUTE, 1);
        String startTime = DateUtil.format(newDate, "yyyy-MM-dd HH:mm:ss");
        return startTime;
    }

    /**
     * 随机生成验证码(数字英文字母)
     *
     * @return
     */
    public static String getVerifyCode(int length) {
        String strCode = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGJKLZXCVBNM1234567890";
        String result = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(strCode.length());
            char c = strCode.charAt(index);
            result += c;
        }
        return result;

    }

    /**
     * 随机生成验证码(纯数字数字)
     *
     * @return
     */
    public static String getVerifyNumCode(int length) {
        String strCode = "123456789012345678901234567890";
        String result = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(strCode.length());
            char c = strCode.charAt(index);
            result += c;
        }
        return result;

    }

    /**
     * 获取用户ip
     *
     * @param request
     * @return
     * @Autowired
     */
    public static String getRemortIP(HttpServletRequest request) {
        if (null == request.getHeader("x-forwarded-for")) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     * 拼接被点赞的用户id和点赞的人的id作为key。格式 222222::333333
     *
     * @param likedUserId 被点赞的人id
     * @param likedPostId 点赞的人的id
     * @return
     */
    public static String getLikedKey(String likedUserId, String likedPostId) {
        StringBuilder builder = new StringBuilder();
        builder.append(likedUserId);
        builder.append("::");
        builder.append(likedPostId);
        return builder.toString();
    }

    /**
     * 递归处理权限菜单
     *
     * @param permisss
     * @return
     */
    public static List<Permission> mergeMenuList(List<Permission> permisss) {
        List<Permission> permissionNew = new ArrayList<>();
        Optional.ofNullable(permisss).orElse(new ArrayList<>())
                .forEach(p -> {
                    if (p.getPParentId() == 0) {
                        CommonUtils.mergeMenu(p, permisss);
                        permissionNew.add(p);
                    }

                });
        return permissionNew;
    }

    public static Permission mergeMenu(Permission parent, List<Permission> permisss) {
        Optional.ofNullable(permisss).orElse(new ArrayList<>())
                .forEach(child -> {
                    if (child.getPParentId().equals(parent.getPId())) {
                        CommonUtils.mergeMenu(child, permisss);
                        parent.getChildren().add(child);
                    }
                });
        return parent;
    }

    /**
     * 合并菜单数据进行展示
     *
     * @param allHave 所有的权限菜单(递归处理)
     * @param pHave   用户角色持有的权限菜单(非递归处理)
     * @return
     */
    public static List<PermissionVo> mergePermission(List<Permission> allHave, List<Permission> pHave) {
        List<PermissionVo> permissionVos = new ArrayList<>();
        Map<Integer, Permission> pHaveMap = new HashMap<>();
        if (pHave.size() > 0) {
            pHaveMap = pHave.stream().collect(Collectors.toMap(Permission::getPId, p -> p));
        }
        PermissionVo vo = null;
        for (Permission p : allHave) {
            if (pHaveMap.containsKey(p.getPId())) {
                vo = PermissionVo.builder().id(p.getPId())
                        .title(p.getPName()).href(p.getPUrl())
                        .pId(p.getPParentId())
                        .pIds(p.getPParentIds())
                        .checked(true).build();
            } else {
                vo = PermissionVo.builder().id(p.getPId())
                        .title(p.getPName()).href(p.getPUrl())
                        .pId(p.getPParentId())
                        .pIds(p.getPParentIds())
                        .checked(false).build();
            }
            // 判断子集
            if (p.getChildren().size() > 0) {
                mergePermissionChild(vo, p.getChildren(), pHaveMap);
            }
            permissionVos.add(vo);
        }
        return permissionVos;
    }

    public static PermissionVo mergePermissionChild(PermissionVo vo, List<Permission> child, Map<Integer, Permission> pHaveMap) {
        PermissionVo newVo = null;
        List<PermissionVo> children = new ArrayList<>();
        for (Permission p : child) {
            if (vo.getId().equals(p.getPParentId())) {
                if (pHaveMap.containsKey(p.getPId())) {
                    newVo = PermissionVo.builder().id(p.getPId())
                            .title(p.getPName()).href(p.getPUrl())
                            .pId(p.getPParentId())
                            .pIds(p.getPParentIds())
                            .checked(true).build();
                } else {
                    newVo = PermissionVo.builder().id(p.getPId())
                            .title(p.getPName()).href(p.getPUrl())
                            .pId(p.getPParentId())
                            .pIds(p.getPParentIds())
                            .checked(false).build();
                }
                // 判断子集
                if (p.getChildren().size() > 0) {
                    mergePermissionChild(newVo, p.getChildren(), pHaveMap);
                }
                children.add(newVo);
            }
        }
        vo.setChildren(children);
        return vo;
    }
}
